package com.powernode.controller;

import com.powernode.api.model.User;
import com.powernode.api.service.UserService;
import com.powernode.service.KuaiQianService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.Map;

@Controller
public class KuaiQianController {

    @DubboReference(interfaceClass = UserService.class,version = "1.0.0")
    private UserService userService;

    @Autowired
    private KuaiQianService kuaiQianService;

    /*接收 来自前端的 支付请求*/
    @GetMapping("/kq/receive/pay")
    public String receiveFrontPay(@RequestParam("uid") Integer uid, @RequestParam("money") BigDecimal money, Model model) {
        /*接收参数*/
        /*验证参数*/
        if (uid!=null&&uid>0&&money.doubleValue()>0){
            /*查询用户 确定用户是否是 系统中的*/
            User user = userService.queryUserById(uid);
            if (user!=null){
                /*生成 快钱 支付接口所需要的 参数数据*/
//                model.addAttribute("inputCharset","1");
                Map<String, String> data = kuaiQianService.generateKqFormData(uid, user.getPhone(), money);
                /*将map集合的 每个数据 存入 model  key 作为 model key map的 value 作为  model 的value*/
                model.addAllAttributes(data);
                /*数据库中  recharge_record 生成 充值订单数据 状态 0  正在充值中*/
                kuaiQianService.addRecharge(uid,money,data);
                /* 扩展 把 订单号  存入 redis  用于 其他接口*/
                kuaiQianService.addOrderIdToRedis(data.get("orderId"));
                return "kqForm";
            }
        }
        return "err";
    }

    /*快钱异步通知 所访问的  接收快钱发送的 支付 结果*/
    @GetMapping("/kq/notify")
    @ResponseBody
    /*快钱请求时传递的参数 都在 request对象中*/
    public String kqNotify(HttpServletRequest request){
        System.out.println("快钱异步通知 访问了 该 请求");
        Enumeration<String> parameter = request.getParameterNames();
        StringBuffer buffer = new StringBuffer();
        while (parameter.hasMoreElements()){
            String name = parameter.nextElement();
            String value = request.getParameter(name);
            System.out.println("name="+name+"value="+value);
            buffer.append(name+"=").append(value).append("&");
        }
        System.out.println(buffer);

        kuaiQianService.handleKuaiQianNotify(request);

        return "<result>1</result><redirecturl>http://www.yoursite.com/show.asp</redirecturl>";
    }
}
